var arrayIds = new Array();
var userIds = new Array();
$(function () {

    // 加载班级成员
    listClassesMember(1);

    $('body')
        .on('click', 'i.fa-eye-on', function () { // 查看学员
            var userId =$(this).parents('tr').find('input[type="checkbox"]').data('id');
            parent.layer.open({
                type: 2,
                title: '<strong>查看学员</strong>',
                shadeClose: false,
                shade: [0.3, '#000000'],
                maxmin: true,
                content: baseloaction + '/admin/user/cus/userInfo?userId='+userId,
                area: winArea,
                btn: ['关闭'],
                yes: function () {
                    parent.layer.closeAll();
                }
            });
        })
        .on('click', 'i.fa-bell', function () { // 发布系统消息
            var userId = $(this).parent('a').data('user');
            var classId = $('#classesId').val();
            bellBatch(userId,classId);
        })
        .on('click', '#classes-member-import', function () { // 导入学员
            selectMember();
        })
        .on('click', '#classes-homework-arrange', function () { // 布置作业
            var classesId = $('#classesId').val();
            getRedirectMenu(baseloaction + '/admin/examination/paper/initAddTask?classesId=' + classesId);
        })
        .on('click', '#frozenBatch', function () { // 批量封禁
            var ids = getChecked(2);
            if (!ids) {
                icModale(0, '请选择要操作的班级成员');
                return;
            }
            icModale(2, '确认批量封禁选中的班级成员', '', function () {
                updateClassesMemberStatus(ids, 2);
            });
        })
        .on('click', '#historyBatch', function () { // 批量恢复
            var ids = getChecked(1);
            if (!ids) {
                icModale(0, '请选择要操作的班级成员');
                return;
            }
            icModale(2, '确认批量恢复选中的班级成员', '', function () {
                updateClassesMemberStatus(ids, 1);
            });
        })
        .on('click', '#bellBatch', function () { // 批量通知
            var ids = getChecked(3);
            var classId = $('#classesId').val();
                bellBatch(ids,classId);
        })
        .on('click', '#btn1, #btn2', function () { // 搜索
            listClassesMember(1);
        })
        .on('click', 'i.fa-arrow-up', function () { // 升为管理员
            var ids = $(this).parents('tr').data('id');
            icModale(2, '确认升为管理员', '', function () {
                updateClassesMemberIdentity(ids, 2);
            });
        })
        .on('click', 'i.fa-arrow-down', function () { // 取消管理员
            var ids = $(this).parents('tr').data('id');
            icModale(2, '确认取消管理员', '', function () {
                updateClassesMemberIdentity(ids, 1);
            });
        })
        .on('click', 'i.fa-ban', function () { // 单个封禁
            var ids = $(this).parents('tr').data('id');
            icModale(2, '确认封禁选中的班级成员', '', function () {
                updateClassesMemberStatus(ids, 2);
            });
        })
        .on('click', 'i.fa-history', function () { // 单个恢复
            var ids = $(this).parents('tr').data('id');
            icModale(2, '确认恢复选中的班级成员题', '', function () {
                updateClassesMemberStatus(ids, 1);
            });
        }).on('click','#upload_img',function () {
            upload_img();
        }).on('click','#teacher_list .fa-close',function () {
               var that = $(this).parent("a");
        parent.layer.confirm("确认要删除班主任吗？", {
            icon: 3,
            title: '提示',
            btn: ['确认', '取消'],
            shade: [0.3, '#000000']
        }, function (index) {
            deleteTeacher(that);
        });
    }).on('click','#teacher_list .fa-close',function () {
        var that = $(this).parent("a");
        parent.layer.confirm("确认要删除班主任吗？", {
            icon: 3,
            title: '提示',
            btn: ['确认', '取消'],
            shade: [0.3, '#000000']
        }, function (index) {
            deleteTeacher(that);
        });
    }).on('click','.deleteLetter',function () {
        var that = $(this);
        parent.layer.confirm("确认要删除消息吗？", {
            icon: 3,
            title: '提示',
            btn: ['确认', '取消'],
            shade: [0.3, '#000000']
        }, function (index) {
            deleteReceiveClassAfficheIds(that);
        });

    }).on("ifChanged","input[name=id]",function(){
        var that=$(this);
        if(that.prop("checked")){
            arrayIds.push(that.val());
            userIds.push(that.data("id"));
        }else {
            arrayIds.splice($.inArray(that.val(), arrayIds));
            userIds.splice($.inArray(that.data("id"), userIds));
        };
        //
    }).on('click','#editBrief',function(){
        editBrief();
    });


    /**
     * 删除班主任
     */
    function deleteTeacher(that) {
        var id =$(that).data("id");
        $.ajax({
            url: baseloaction + '/admin/classes/member/deleteClassTeacher',
            data: {'id': id},
            dataType: 'json',
            type: 'post',
            success: function (response) {
                icModale(0, response.message);
                if (response.success) {
                    $(that).parent("p").remove();
                } else {
                    icModale(0, response.message);
                }
            },
            error: function () {
                icModale(0, '系统繁忙，请稍候再试');
            }
        });
    }
    /**
     * 删除班主任
     */
    function deleteReceiveClassAfficheIds(that) {
       var  afficheRandoms = that.attr("data-afficherandom")
        $.ajax({
            url: baseloaction + '/admin/classes/member/deleteReceiveClassAfficheIds',
            data: {'afficheRandoms': afficheRandoms},
            dataType: 'json',
            type: 'post',
            success: function (response) {
                if(response.success==true){
                    that.parents("tr").remove();
                }
                icModale(0, response.message);
            },
            error: function () {
                icModale(0, '系统繁忙，请稍候再试');
            }
        });
    }
    /**
     * 发送消息弹窗
     *
     * @param callback
     */
    function sendNotice(callback) {
        parent.layer.open({
            type: 1,
            area: ['800px', '400px'],
            skin: 'layui-layer-demo',
            title: '通知学员',
            content: '<div class="m-t m-r m-l m-b"><textarea class="form-control" style="height: 260px;width: 760px;resize: none;" placeholder="请填写要通知学员的内容" id="context"></textarea></div>',
            btn: '确定',
            yes: function (index, layero) {
                var context = layero.find('#context').val();
                if (!context){
                    return icModale(0,'请输入要通知的内容');
                }
                var name = $("#name").val();
                var id = $('#classesId').val();
                context += '[' + '<a href="' + baseloaction + '/web/classes/info?id=' + id + '">' + name + '</a>' + ']';
                callback(context);
            }
        });
    }

    /**
     * 发送通知
     *
     * @param ids
     */
    function bellBatch(ids,classId) {
        sendNotice(function (context) {
            var params = {'userIds': ids, 'context': context,'classId':classId};
            params = JSON.stringify(params);
            $.ajax({
                url: baseloaction + "/admin/classes/member/sendMemberNotice",
                type: "post",
                data: params,
                dataType: "json",
                contentType: 'application/json;charset=utf-8',
                success: function (response) {
                    if (response.success) {
                        parent.layer.closeAll();
                        icModale(0, response.message);
                        arrayIds=[];
                        userIds=[];
                    } else {
                        icModale(0, response.message);
                    }
                },
                error: function () {
                    icModale(0, '系统繁忙，请稍后再试');
                }
            });
        });
    }

    /**
     * 获得选中的班级成员
     * @returns {string}
     */
    function getChecked(status) {
        if (status == 3){
            return userIds.join(',');
        } else{
            return  arrayIds.join(',');
        }
    }
    /**
     * 是否获取该条班级记录的id的谓词
     * @param parent tr元素
     * @param status 更新后的状态
     * @returns {boolean}
     */
    function predicate(parent, status) {
        switch (status) {
            case 1:
                return parent.find('i.fa-history').length > 0;
            case 2:
                return parent.find('i.fa-ban').length > 0;
            case 3:
                return parent.find('i.fa-bell').length > 0;
            default:
                return false;
        }
    }

    /**
     * 选择班级成员
     */
    function selectMember() {
        var subjectIds = $('#subjectIds').val();
        selectUser('checkbox', subjectIds);
    }

    /**
     * 更新班级成员状态
     * @param ids
     * @param status 1.正常 2.封禁
     */
    function updateClassesMemberStatus(ids, status) {
        $.ajax({
            url: baseloaction + '/admin/classes/member/updateMemberStatus',
            data: {'ids': ids, 'status': status},
            dataType: 'json',
            type: 'post',
            success: function (response) {
                icModale(0, response.message);
                if (response.success) {
                    var array = (ids + "").split(",");
                    array.forEach(function (value) {
                        updatePageForStatus(value, status);
                    });
                    setAllUncheckIds();
                } else {
                    icModale(0, response.message);
                }
            },
            error: function () {
                icModale(0, '系统繁忙，请稍候再试');
            }
        });
    }

    /**
     * 更新班级成员身份
     * @param ids 班级成员id
     * @param identity 1.普通学员 2.班级管理员 3.班主任
     */
    function updateClassesMemberIdentity(ids, identity) {
        if (!ids) {
            icModale(0, '请选择要操作的班级成员');
            return;
        }
        $.ajax({
            url: baseloaction + '/admin/classes/member/updateMemberIdentity',
            data: {'ids': ids, 'identity': identity},
            dataType: 'json',
            type: 'post',
            success: function (response) {
                icModale(0, response.message);
                if (response.success) {
                    var array = (ids + "").split(",");
                    array.forEach(function (value) {
                        updatePageForIdentity(value, identity);
                    });
                    setAllUncheckIds();
                }
            },
            error: function () {
                icModale(0, '系统繁忙，请稍候再试');
            }
        });
    }

    /**
     * 更新页面
     * @param id 班级成员id
     * @param status 1.正常 2.封禁
     */
    function updatePageForStatus(id, status) {
        var tr = $('tr[data-id=' + id + ']');
        switch (status) {
            case 1:
                tr.find('i.fa-history').attr('class', 'fa fa-ban').parent('a').attr('data-original-title', '封禁');
                tr.find('td[data-status]').html('<span class="label label-info">正常</span>');
                break;
            case 2:
                if (tr.find('i.fa-ban').length > 0) {
                    tr.find('i.fa-ban').attr('class', 'fa fa-history').parent('a').attr('data-original-title', '恢复');
                    tr.find('td[data-status]').html('<span class="label label-danger">封禁</span>');
                }
                break;
        }
    }

    /**
     * 更新页面
     * @param id 班级成员id
     * @param identity 1.普通学员 2.班级管理员 3.班主任
     */
    function updatePageForIdentity(id, identity) {
        var tr = $('tr[data-id=' + id + ']');
        switch (identity) {
            case 1:
                tr.find('i.fa-arrow-down').attr('class', 'fa fa-arrow-up').parent('a').attr('data-original-title', '管理员');
                break;
            case 2:
                tr.find('i.fa-arrow-up').attr('class', 'fa fa-arrow-down').parent('a').attr('data-original-title', '撤职');
                break;
        }
    }
    function upload_img() {
        initUpdateFileWin({
            fileType:'img',//文类类型["img","ico","xls","pdf","zip"]
            callback:'uploadClassImgCallback',
            cut:true,//开启剪切
            imgSize:DEFAULT_CLASS_IMG_SIZE,//剪切上传后生成图片的规格（开启剪切才起使用）
            aspectRatio:1/1//剪切区域的高宽比例（开启剪切才起使用）
        });
    }

});

function getClassesId() {
    return $('#classesId').val();
}

/**
 * 加载班级成员数据
 * @param pageNo
 */
function listClassesMember(pageNo) {
    var params = $('#search-form').serializeJSON();
    params.classesId = getClassesId();
    params = JSON.stringify(params);
    var obj = {
        url: baseloaction + '/admin/classes/member/ajaxClassesMemberPage',//请求URL
        contextId: 'oc-ibox-content',//响应内容页面设置内容ID
        params: params,//请求参数
        pageNo: pageNo,//页码
        pageCall: listClassesMember, //分页回调加载数据(点击上下页时调用,该方法也在加载页面完成时调用)
        selectAllId: 'all-select',        //全选框ID
        callback: function () {
            $('#count').html(total);
            setAllIds();
        }
    };
    ajaxGetListData(obj);
}

/**
 * 保存选择的班级成员
 * @param ids
 */
function saveClassesMember(ids) {
    if (!ids) {
        icModale(0, '选择导入的成员');
        return;
    }
    $.ajax({
        url: baseloaction + '/admin/classes/member/saveMemberBatch',
        data: {'classesId': getClassesId(), 'memberIds': ids, 'identity': 1},
        type: 'post',
        success: function (response) {
            icModale(0, response.message);
            if (response.success) {
                listClassesMember(1);
            }
        }
    })
}
/**
 * 选择班级成员回调
 * @param user
 */
function selectUserCallback(user) {
    if (user.length > 0) {
        var ids = user.map(function (v, i) {
            return v.id;
        }).join(',');
        saveClassesMember(ids)
    }
}

//图片上传回调
function uploadClassImgCallback(result) {
    if(result!=null){
        $("#class_img").attr("src",result.pcUrlMap.small);
        var id =  $("#classesId").val();
        $.ajax({
            url: baseloaction + '/admin/classes/saveClassesImg',
            data: {'imageJson': encodeURIComponent(JSON.stringify(result)), 'id': id},
            type: 'post',
            success: function (response) {
                icModale(0, response.message);
                if(response.success==true){
                    setTimeout(function(){
                        parent.layer.close(index);
                        window.location=baseloaction+"/admin/classes/initUpdate?id="+id+"&step=2"
                    },500);
                }
            }
        });
    }
}

function setAllIds() {
    if(arrayIds.length>0){
        var obj = $('input[name=id]');
        $.each(obj, function (i, item) {
            if( $.inArray($(item).val(), arrayIds)!=-1){
                $(item).iCheck('check');
            }else{
                $(item).iCheck('uncheck');
            }
        });
    }

}


function setAllUncheckIds() {
    if(arrayIds.length>0){
        var obj = $('input[name=id]');
        $.each(obj, function (i, item) {
            $(item).iCheck('uncheck');
        });
        arrayIds=[];
        userIds =[];
    }

}

function editBrief(){

    parent.layer.open({
        type: 1,
        area: ['800px', '400px'],
        skin: 'layui-layer-demo',
        title: '修改班级简介',
        content: '<div class="m-t m-r m-l m-b"><textarea class="form-control" style="height: 260px;width: 760px;resize: none;" placeholder="最多填写255个字符" id="context"></textarea></div>',
        btn: '确定',
        yes: function (index, layero) {
            var context = layero.find('#context').val();
            if (!context){
                return icModale(0,'请输入要通知的内容');
            }
            if(context.length>255){
                return icModale(0,'填写的内容不能超过255个字符');
            }

            $.ajax({
                url: baseloaction + '/admin/classes/editBrief',
                data: {'summary': context, 'id': $("#classesId").val()},
                type: 'post',
                success: function (response) {
                    icModale(0, response.message);
                    if(response.success==true){
                        setTimeout(function(){
                            parent.layer.close(index);
                            $("#summary").text(context);
                        },500);
                    }
                }
            });

        }
    });

};

